<template>
  <div>
    <div class="category_box">
      <a-card style="width: 100% ;height:100%">
        <span v-show="parentId==0" slot="title">一级分类列表</span>
        <div v-show="parentId!=0" slot="title">
          <span @click="showCategorys" style="font-size:700;color:rgb(60, 166, 255)">一级分类列表</span> &nbsp;&nbsp;&nbsp;
          <a-icon type="arrow-right" />
          <span>{{this.parentName}}</span>
        </div>
        <a-button type="primary" slot="extra" @click="showModal">添加类别</a-button>
        <div>
          <a-table
            bordered
            :dataSource="parentId ==0 ? categorys:subCategorys"
            :columns="parentId==0?columns:[columns[0]]"
            :pagination="{defaultPageSize: 5, showQuickJumper: true}"
            :loading="loading"
          >
            <template slot="name" slot-scope="text, record">
              <editable-cell :text="text" @change="onCellChange(record, 'name', $event)" />
            </template>
            <template v-if="parentId == 0" slot="operation" slot-scope="text, record">
              <a href="javascript:;" @click="showSubCategorys(record,'subcategory',$event)">查看子分类</a>
            </template>
          </a-table>
          <div class="add_box">
            <!-- <a-button type="primary" @click="handleAdd">Open Modal with async logic</a-button> -->
            <a-modal
              title="Title"
              :visible="addFormVisible"
              @ok="handleOk"
              :confirmLoading="confirmLoading"
              @cancel="handleCancel"
            >
              <addform :categorys="categorys" @bindAddForm="bindAddForm" />
            </a-modal>
          </div>
        </div>
      </a-card>
    </div>
  </div>
</template>
<script>
/*
 * EditableCell Code https://github.com/vueComponent/ant-design-vue/blob/master/components/table/demo/EditableCell.vue
 */
import EditableCell from "./EditableCell";
import {
  reqCategorys,
  reqUpdateCategory,
  reqAddCategory
} from "../../api/index";
import { message } from "ant-design-vue";
import addform from "./addForm/addForm";
export default {
  components: {
    EditableCell,
    addform
  },
  data() {
    return {
      //table是否是loading状态
      loading:true,
      parentId: 0,
      parentName: "",
      categorys: [], // 一级分类列表
      subCategorys: [], // 二级分类列表
      ModalText: "Content of the modal",
      visible: true,
      confirmLoading: false,
      //添加的模块
      addFormVisible: false,
      // categorys: {},
      //列表中的分类列表
      dataSource: [],
      columns: [
        {
          title: "分类名称",
          dataIndex: "name",
          wid: "",
          width: "70%",
          scopedSlots: { customRender: "name" }
        },
        {
          title: "操作",
          dataIndex: "operation",
          scopedSlots: { customRender: "operation" }
        }
      ]
    };
  },
  created() {
    this.getCategorys();
    this.form = this.$form.createForm(this, { name: "normal_login" });
  },
  methods: {
    //查看子分类列表
    async showSubCategorys(record, category, event) {
      this.loading = true
      this.parentId = record.key;
      this.parentName = record.name;
      var categoryId = record.key;
      const result = await reqCategorys(categoryId);
      var data = result.data;
      this.subCategorys.splice(0, this.subCategorys.length);
      data.forEach((item, index) => {
        var key = item._id;
        var name = item.name;
        var value = item;
        this.subCategorys.push({ key, name, value });
      });
     
      this.loading = false
    },
    //从二级分类列表到一级列表
    showCategorys() {
      console.log("showCategorys");
      this.parentId = 0;
    },
    //监听<addform>发射bindAddForm事件  接收其传入的form,并绑定到本组件的this上
    bindAddForm(form) {
      this.form = form;
    },
    //获取一级分类的列表
    async getCategorys() {
      const result = await reqCategorys();
      var categorys = result.data;
      categorys.forEach((data, index) => {
        var item = {
          key: data._id,
          name: data.name,
          //该分类的所有信息都存入value中
          value: data
        };
        this.categorys.push(item);
        
      });
      this.loading = false
   },
    //修改分类名称
    async onCellChange(record, dataIndex, value) {
      var categoryId = record.key;
      var categoryName = value;
      const result = await reqUpdateCategory({ categoryId, categoryName });
      if (result.status == 0) {

        //后台修改成功后更改对应在data中的数据，不然前后台不同步
        if(!this.parentId){
            var index = this.categorys.indexOf(record)
            record.name = value
            this.categorys.splice(index,1,record)
        }else{
            var index = this.subCategorys.indexOf(record)
            record.name = value
            this.subCategorys.splice(index,1,record)
        }
        message.success("修改成功!");
      } else {
        message.error("修改失败!");
      }
    },
    onDelete(key) {
      const dataSource = [...this.dataSource];
      this.dataSource = dataSource.filter(item => item.key !== key);
    },
    //添加分类
    async handleAdd() {
      //  var parentId = 0
      //  var categoryName ;
      // var result = await reqAddCategory(categoryName, parentId)
    },
    showModal() {
      this.addFormVisible = true;
    },
    //监听 添加模态框的ok按钮事件
    handleOk(e) {
      this.confirmLoading = true;
      //验证表单
      this.form.validateFields(async (err, values) => {
        if (!err) {
          const parentId = values.parentId;
          const categoryName = values.categoryName;
          const result = await reqAddCategory(categoryName, parentId);

          this.confirmLoading = false;
          if (result.status == 0) {
            var data = result.data;
            var item = { key: data._id, name: data.name, value: data };
            if (data.parentId == 0) {
              this.categorys.push(item);
            }else{
              this.subCategorys.push(item)
            }
            this.addFormVisible = false;
            message.success("添加成功!");
          } else {
            message.error("添加失败!");
          }
        }
      });
    },
    //监听 添加模态框的cancel按钮事件
    handleCancel(e) {
      console.log("Clicked cancel button");
      this.addFormVisible = false;
    }
  }
};
</script>
<style>
.editable-cell {
  position: relative;
}

.editable-cell-input-wrapper,
.editable-cell-text-wrapper {
  padding-right: 24px;
}

.editable-cell-text-wrapper {
  padding: 5px 24px 5px 5px;
}

.editable-cell-icon,
.editable-cell-icon-check {
  position: absolute;
  right: 0;
  width: 20px;
  cursor: pointer;
}

.editable-cell-icon {
  line-height: 18px;
  display: none;
}

.editable-cell-icon-check {
  line-height: 28px;
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}

.editable-cell-icon:hover,
.editable-cell-icon-check:hover {
  color: #108ee9;
}

.editable-add-btn {
  margin-bottom: 8px;
}
</style>
